#include "common.h"
#include "clientcommands.h"
#include "serialization.h"
#include "commands.h"

using namespace std;

struct sockaddr_in server_addr, client_addr_message;
string username, servername;


int main(int argc, char *argv[])
{

    if (argc < 3)
    {
        error("Not enough parameters. Usage: cmclient username servername");
    }
    username = argv[1];
    servername = argv[2];

    LOG << "Username is " << username << ", server address is " <<  servername << endl;

    // Opening socket
    if ((socket_message = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
        error("Could not open socket");

    // Init Server sockaddr_in
    server_addr = generate_sockaddr_int(inet_addr(servername.c_str()), htons(UDP_PORT_SERVER));
    client_addr_message = generate_sockaddr_int(htonl(INADDR_ANY), htons(UDP_PORT_CLIENT));

    if (bind(socket_message, (struct sockaddr*)&client_addr_message,  sizeof(client_addr_message)) < 0)
        error("Could not bind to the socket");


    while(1)
    {
        string line;
        getline(cin, line);
        vector<string> words = str2words(line);

        LOG << "Received message || " << line << "|| \n";

        if(words[0] ==  "quit")
        {
            LOG << "Quitting ..." << endl;
            return 0;
        }

        handleCommand(words, line);

    }
    return 0;

}
